﻿package com.eve.eplus.common.db;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; 

import com.eve.eplus.common.app.Configuration;
import com.eve.eplus.common.app.Constants;
import com.eve.eplus.common.tools.LogTools;
 
import android.content.Context;
import android.content.res.AssetManager; 
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * 数据库管理类
 * @author Norsie
 * @created 12-11-29
 */
public class DBOpenHelper extends SQLiteOpenHelper {
      
    private Context context;

    
    public DBOpenHelper(Context context) {
     
        super(context, Configuration.DATA_PATH + Configuration.DB_NAME, null, Constants.DATABASE_VERSION);
        this.context = context;
    }

    public DBOpenHelper(Context context, String name,
            CursorFactory factory, int version) {
        
        super(context, name, factory, version);
        this.context = context;
    }

    /**
     * 用户第一次使用软件时调用的操作
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        LogTools.info("数据库消息:创建数据库。");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        updateSQL(db,oldVersion,newVersion);    
    }

    /**
     * 升级脚本
     * @param db 数据库
     * @param oldVersion 旧版本号
     * @param newVersion 新版本号
     */
    private void updateSQL(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        
        String[] fileNameArray = getSQLFileList();
        
        if(fileNameArray == null) return;
        
        executeSQL(db, oldVersion, newVersion, fileNameArray);
    }

    /**
     * 执行SQL文件
     * @param db
     * @param oldVersion
     * @param newVersion
     * @param fileNameArray
     */
    private void executeSQL(SQLiteDatabase db, int oldVersion, int newVersion,
            String[] fileNameArray) {
        int lineNum = 0;
        String sqlOneLine = "";
        
        BufferedReader read = null;
        InputStream input = null;
        try {
            for (String file : fileNameArray) {
                
                int currentVersion = getSQLVersion(file);
                if (currentVersion > oldVersion && currentVersion <= newVersion) {
                    //获取文件&执行升级脚本
                    input = context.getAssets().open("EVE_DB/" + file);
                    read = new BufferedReader(new InputStreamReader(input));
                    
                    db.beginTransaction();
                    while ((sqlOneLine = read.readLine()) != null) {
                        lineNum++;
                        
                        sqlOneLine = sqlOneLine.trim();
                        
                        if ("".equals(sqlOneLine)  || sqlOneLine == null)
                            continue;
                        
                        if ('#' != sqlOneLine.charAt(0)) {                          
                            db.execSQL(sqlOneLine);
                        }
                    }
                    db.setVersion(currentVersion);
                    db.setTransactionSuccessful();
                    db.endTransaction();

                    input.close();
                    read.close();
                }
            }
        } catch (IOException e) {
            // TODO lee Auto-generated catch block 
            LogTools.error("rowNum:" + lineNum + " , " + e.getMessage() + ","+ e.getCause(),e);
            e.printStackTrace();
        }
    }

    /**
     * 获取所有SQL文件
     * @return
     */
    String[] getSQLFileList() {
        String[] fileNameArray = null;
        AssetManager am = context.getAssets();

        try {
            // 获取Assert下面fpiSQL文件夹下的所有文件
            fileNameArray = am.list("EVE_DB");
        } catch (IOException e1) {

            e1.printStackTrace();
            return null;
        }
        return fileNameArray;
    }
    
    /**
     * 通过文件名确定文件的版本
     * 
     * @param fileName
     * @return
     */
    private int getSQLVersion(String fileName) {
        // TODO Auto-generated method stub

        if (fileName == null || fileName == "")
            return -1;
        String v = fileName.substring(1, fileName.indexOf("."));
        try {

            return Integer.parseInt(v);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 根据版本号进行更新
     * 
     * @param db
     * @param mNewVersion
     */
    public void checkVersionCreate(SQLiteDatabase db, int mNewVersion) {
        int version = db.getVersion();
        if (version != mNewVersion) {
            db.beginTransaction();
            try {
                if (version == 0) {
                    onCreate(db);
                } else {
                    onUpgrade(db, version, mNewVersion);
                }
                db.setVersion(mNewVersion);  
                db.setTransactionSuccessful();
            } finally {
                db.endTransaction();
            }
        }
    }
}